using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace MimeCloud.GDI.Imaging
{
    public class Saving
    {

        public static void SaveImageAsJPEG(Image image, string pathtosave)
        {
            //resize image
            image.Save(pathtosave, GetEncoderInfo("image/jpeg"), GetQualityParams());
        }
        public static void SaveImageAsJPEG(Image image, ref Stream streamToSave)
        {
            image.Save(streamToSave, GetEncoderInfo("image/jpeg"), GetQualityParams());
        }
      

        public static EncoderParameters GetQualityParams()
        {
            //Set encoder settings
            Encoder qualityEncoder = Encoder.Quality;
            EncoderParameter ratio = new EncoderParameter(qualityEncoder, 90L);
            EncoderParameters codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;

            return codecParams;
        }

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            } return null;
        }

        public static string SaveToTempFile(Image image)
        {
            string name = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".jpgtmp";
            SaveImageAsJPEG(image,name);
            return name;
        }
    }
}
